package com.ibeeking.found.uaa.c.config.auth.adapter;

import com.ibeeking.found.uaa.c.config.advice.ClientOauthExceptionTranslator;
import com.ibeeking.found.uaa.c.config.auth.sms.WxAppletsTokenGranter;
import com.ibeeking.found.uaa.c.config.auth.sms.WxSmsCodeTokenGranter;
import com.ibeeking.found.uaa.c.config.filter.ClientExceptionEntryPoint;
import com.ibeeking.found.uaa.c.config.filter.CustomClientCredentialsTokenEndpointFilter;
import com.ibeeking.found.uaa.c.service.IClientUserDetailsService;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.oauth2.config.annotation.configurers.ClientDetailsServiceConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configuration.AuthorizationServerConfigurerAdapter;
import org.springframework.security.oauth2.config.annotation.web.configuration.EnableAuthorizationServer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerEndpointsConfigurer;
import org.springframework.security.oauth2.config.annotation.web.configurers.AuthorizationServerSecurityConfigurer;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2RequestFactory;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.client.ClientCredentialsTokenGranter;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeTokenGranter;
import org.springframework.security.oauth2.provider.implicit.ImplicitTokenGranter;
import org.springframework.security.oauth2.provider.password.ResourceOwnerPasswordTokenGranter;
import org.springframework.security.oauth2.provider.refresh.RefreshTokenGranter;
import org.springframework.security.oauth2.provider.token.AuthorizationServerTokenServices;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 认证服务配置
 *
 * @Author ibeeking
 */
@Configuration
@EnableAuthorizationServer
public class AuthorizationServerConfig extends AuthorizationServerConfigurerAdapter {

    @Resource
    private AuthenticationManager authenticationManager;
    @Resource
    private JwtAccessTokenConverter jwtAccessTokenConverter;
    @Resource
    private IClientUserDetailsService userDetailsServiceImpl;
    @Resource
    private ClientDetailsService clientDetailsServiceImpl;
    @Resource
    private ClientExceptionEntryPoint clientExceptionEntryPoint;

    /***
     * /oauth/authorize：授权端点
     * /oauth/token：令牌端点
     * /oauth/confirm_access：用户确认授权提交端点
     * /oauth/error：授权服务错误信息端点
     * /oauth/check_token：用于资源服务访问的令牌解析端点
     * /oauth/token_key：提供公有密匙的端点，如果使用JWT令牌的话
     */

    /**
     * 客户端信息配置
     */
    @Override
    public void configure(ClientDetailsServiceConfigurer clients) throws Exception {
        clients.withClientDetails(clientDetailsServiceImpl);
    }

    /**
     * 配置授权（authorization）以及令牌（token）的访问端点和令牌服务(token services)
     */
    @Override
    public void configure(AuthorizationServerEndpointsConfigurer endpoints) {
        endpoints.tokenGranter(new CompositeTokenGranter(this.getTokenGranters(endpoints.getClientDetailsService(), endpoints.getTokenServices(), endpoints.getAuthorizationCodeServices(), endpoints.getOAuth2RequestFactory())));
        endpoints.authenticationManager(authenticationManager)
                .accessTokenConverter(jwtAccessTokenConverter)
                .reuseRefreshTokens(false)
                .userDetailsService(userDetailsServiceImpl)
                .exceptionTranslator(new ClientOauthExceptionTranslator())
        ;
    }

    /**
     * 允许表单认证
     */
    @Override
    public void configure(AuthorizationServerSecurityConfigurer security) {
        CustomClientCredentialsTokenEndpointFilter endpointFilter = new CustomClientCredentialsTokenEndpointFilter(security);
        endpointFilter.afterPropertiesSet();
        endpointFilter.setAuthenticationEntryPoint(clientExceptionEntryPoint.clientExceptionEntryPoint());
        security.addTokenEndpointAuthenticationFilter(endpointFilter);

        security.authenticationEntryPoint(clientExceptionEntryPoint.clientExceptionEntryPoint())
                /**
                 * 允许所有人请求令牌
                 */
                .tokenKeyAccess("isAuthenticated()")
                /**
                 * 已验证的客户端才能请求check_token端点
                 */
                .checkTokenAccess("permitAll()")
        ;
    }

    private List<TokenGranter> getTokenGranters(ClientDetailsService clientDetailsServiceImpl, AuthorizationServerTokenServices tokenServices, AuthorizationCodeServices authorizationCodeServices, OAuth2RequestFactory requestFactory) {
        List<TokenGranter> tokenGranters = new ArrayList<TokenGranter>();
        tokenGranters.add(new AuthorizationCodeTokenGranter(tokenServices, authorizationCodeServices, clientDetailsServiceImpl, requestFactory));
        tokenGranters.add(new RefreshTokenGranter(tokenServices, clientDetailsServiceImpl, requestFactory));
        tokenGranters.add(new ImplicitTokenGranter(tokenServices, clientDetailsServiceImpl, requestFactory));
        tokenGranters.add(new ClientCredentialsTokenGranter(tokenServices, clientDetailsServiceImpl, requestFactory));
        tokenGranters.add(new WxAppletsTokenGranter(tokenServices, clientDetailsServiceImpl, requestFactory, userDetailsServiceImpl));
        tokenGranters.add(new WxSmsCodeTokenGranter(tokenServices, clientDetailsServiceImpl, requestFactory, userDetailsServiceImpl));
        if (authenticationManager != null) {
            tokenGranters.add(new ResourceOwnerPasswordTokenGranter(authenticationManager, tokenServices, clientDetailsServiceImpl, requestFactory));
        }
        return tokenGranters;
    }
}
